package com.kyzh.core.dialog

import android.app.Activity
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import com.kyzh.core.R
import com.kyzh.core.databinding.DialogSendMessageBinding
import com.gushenge.core.toast


private var addtodoDialog:AlertDialog?=null

fun Activity.showSendMessageDialog(hint:String="请评价",listener:String.()->Unit){
    addtodoDialog = AlertDialog.Builder(this, R.style.dialogSoftInput)
        .setView(getThisView(hint,listener))
        .create()
    addtodoDialog?.window?.apply {
        setGravity(Gravity.BOTTOM)

        decorView.setPadding(0, 0, 0, 0)
        val lp: WindowManager.LayoutParams = attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        attributes = lp
    }
    addtodoDialog?.show()
}

private fun Activity.getThisView(hint:String = "",listener: String.() -> Unit): View {
    val view = DialogSendMessageBinding.inflate(LayoutInflater.from(this))
    view.apply {
        etInput.hint = hint
        etInput.showSoftInputFromWindow()
        send.setOnClickListener {
            val content = etInput.text.toString().trim()
            if (content.isNotEmpty()){
                listener(content)
                hideKeyboard(etInput)
                addtodoDialog?.dismiss()
            }else{
                "内容不能为空".toast()
            }
        }
    }

    return view.root
}
fun EditText.showSoftInputFromWindow() {
    isFocusable = true
    isFocusableInTouchMode = true
    requestFocus()
}
fun EditText.hitSoftInputFromWindow() {
    clearFocus()
//    requestFocus()
}
fun Activity.hideKeyboard(editText: View) {
    (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(
        editText.windowToken,
        0
    )
}